package cn.aiyuan;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;


@Slf4j
@Getter
@AllArgsConstructor
class DelayedQueueProducer<T extends Delayed> {

    private final DelayQueue<T> delayQueue = new DelayQueue<>();


    public void put(T delayedUser) {
        log.info("put delayedUser {}", delayedUser);
        delayQueue.put(delayedUser);
    }

    public T take() {
        T element = null;
        try {
            element = delayQueue.take();
            log.info("take {}", element);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return element;
    }


    public T take(long timeout, TimeUnit unit) {
        T element = null;
        try {
            element = delayQueue.poll(timeout,unit);
            log.info("take {}", element);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return element;
    }

    public static void main(String[] args) {
        DelayedQueueProducer<DelayedUser> delayedQueueProducer = new DelayedQueueProducer<>();
        delayedQueueProducer.put(new DelayedUser("d",10000));
        delayedQueueProducer.put(new DelayedUser("a",1000));
        delayedQueueProducer.put(new DelayedUser("b",1500));
        DelayedUser c = new DelayedUser("c", 3000);
        delayedQueueProducer.put(c);

        DelayQueue<DelayedUser> delayQueue = delayedQueueProducer.getDelayQueue();
        System.out.println("delayQueue.remove(c) = " + delayQueue.remove(c));
        while (!delayQueue.isEmpty()){
            System.out.println(delayedQueueProducer.take(5,TimeUnit.SECONDS));
        }
    }
}
